<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Dto\SmartTagStatsDto;
use App\CustHub\Mapper\ChSmartTagContactStatMapper;
use App\CustHub\Mapper\ChSmartTagMapper;
use App\CustHub\Model\ChSmartTag;
use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Snowflake\IdGeneratorInterface;
use Mine\Abstracts\AbstractService;
use Mine\MineCollection;
use Mine\MineResponse;

/**
 * 智能标签客户统计
 */
class ChSmartTagContactStatService extends AbstractService
{
    public $mapper;

    #[Inject]
    protected IdGeneratorInterface $idGenerator;

    public function __construct(ChSmartTagContactStatMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function getStatsList(array $params)
    {
        return $this->getData($params);
    }

    public function exportContactStats(array $params): \Psr\Http\Message\ResponseInterface
    {
        $tagInfo = container()->get(ChSmartTagMapper::class)->findById($params['tag_id']);

        $tagName = $tagInfo->name;

        return (new MineCollection())->export(SmartTagStatsDto::class, '标签数据-'.$tagName, $this->getData($params));
    }

    private function getData(array $params): array
    {
        $startTime = Carbon::now()->subDays(15)->toDateString();
        $statsMap = $this->mapper->model::query()
            ->select(['date','contact_count'])
            ->where('date','>=',$startTime)
            ->where('tag_id',$params['tag_id'])
            ->pluck('contact_count','date')
            ->toArray();

        $days = [];

        for ($i = 1;$i< 15;$i++){
            $days[] = Carbon::now()->subDays($i)->toDateString();
        }

        $list = [];
        foreach ($days as $day){
            if(isset($statsMap[$day])){
                $contactCount = $statsMap[$day];
            }else{
                $contactCount = 0;
            }
            $list[] = [
                'date' => date('m-d',strtotime($day)),
                'contact_count' => $contactCount
            ];
        }
        return $list;
    }

    /**
     * 客户同步
     */
    public function sync(): void
    {
        ChSmartTag::query()
            ->select(['id','main_uid','parent_id','contact_cnt'])
            ->where('parent_id','<>',0)
            ->chunk(1000,function ($item){
                $this->syncToDatabase($item->toArray());
            });
    }

    private function syncToDatabase(array $tagList): void
    {
        $date = Carbon::now()->subDay()->toDateString();
        $batchData = [];
        foreach ($tagList as $item){
            $batchData[] = [
                'id' => $this->idGenerator->generate(),
                'uid' => $item['main_uid'],
                'date' => $date,
                'tag_group_id' => $item['parent_id'],
                'tag_id' => $item['id'],
                'contact_count' => $item['contact_cnt'],
                'created_at' => Carbon::now()->toDateString()
            ];
        }

        $this->mapper->model::insert($batchData);
    }
}